package nero.yncc.com.createart.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;

import nero.yncc.com.createart.R;
import nero.yncc.com.createart.adapter.AdapterShopCarOutSize;
import nero.yncc.com.createart.adapter.AdapterShopCarOutSize_activity;
import nero.yncc.com.createart.base.BaseActivity;
import nero.yncc.com.createart.base.Constants;
import nero.yncc.com.createart.bean.BeanShopCar;
import nero.yncc.com.createart.bean.GodBean;
import nero.yncc.com.createart.custom.IconView;
import nero.yncc.com.createart.interfaces.InterfaceDoSomeThing;
import nero.yncc.com.createart.utils.DialogUtil;
import nero.yncc.com.createart.utils.HttpUtils;

/**
 * Created by nero on 2017/7/9.
 */
@ContentView(R.layout.activity_shopcar)
public class ActivityShopcar extends BaseActivity {
    @ViewInject(R.id.rv_shopcar)
    RecyclerView rv_shopcar;
    @ViewInject(R.id.tv_all_parse)
    TextView tv_all_parse;
    @ViewInject(R.id.icon_all)
    IconView icon_all;
    @ViewInject(R.id.icon_nodata)
    IconView icon_nodata;
    @ViewInject(R.id.tv_hadChoose)
    TextView tv_hadChoose;
    @ViewInject(R.id.tv_goshop)
    TextView tv_goshop;

    AdapterShopCarOutSize adapterShopCar;
    ArrayList<BeanShopCar> arrayList_shopcar;



    @Override
    protected void initView() {
        setTitleBarTitle("购物车");
        arrayList_shopcar = new ArrayList<>();
        adapterShopCar = new AdapterShopCarOutSize(this, mContext, arrayList_shopcar, userBean, true, new InterfaceDoSomeThing() {
            @Override
            public void doSomething(final String some) {
                super.doSomething(some);
                DialogUtil.getConfirmDialog(ActivityShopcar.this, "是否要删除该商品?", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        changeShopcar(some, STATE_DEL);
                    }
                }).show();
            }

            @Override
            public void doSomething() {
                super.doSomething();
                setMoney();
            }
        });
        rv_shopcar.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        rv_shopcar.setAdapter(adapterShopCar);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {
        icon_all.setOnClickListener(this);
        setRight("编辑", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (tv_title_right.getText().equals("编辑")) {
                    for (BeanShopCar beanShopCar : arrayList_shopcar) {
//                        for (BeanShopCar.goods goods:beanShopCar.getList()){
//                            goods.setEdit(true);
//                        }
                        beanShopCar.setEdit(true);
                    }
                    tv_title_right.setText("完成");
                } else {
                    for (BeanShopCar beanShopCar : arrayList_shopcar) {
                        beanShopCar.setEdit(false);
//                        for (BeanShopCar.goods goods:beanShopCar.getList()){
//                            goods.setEdit(false);
//                        }
                    }
                    tv_title_right.setText("编辑");
                }
                adapterShopCar.notifyDataSetChanged();
            }
        });
        tv_goshop.setOnClickListener(this);
    }

    @Override
    public void doClick(int id) {
        switch (id) {
            case R.id.icon_all:
                if (hasChooseAll) {
                    for (BeanShopCar godBean : arrayList_shopcar) {
                        godBean.setChoose(false);
                    }
                    hasChooseAll = false;
                } else {
                    for (BeanShopCar godBean : arrayList_shopcar) {
                        godBean.setChoose(true);
                    }
                    hasChooseAll = true;
                }

                if (hasChooseAll) {
                    icon_all.setTextColor(getResources().getColor(R.color.project_yellow));
                } else {
                    icon_all.setTextColor(getResources().getColor(R.color.textColorGray));
                }
                adapterShopCar.notifyDataSetChanged();
                setMoney();
                break;
            case R.id.tv_goshop:
                //去下单 先进行订单数量校验
                preformOrder();
                break;
        }
    }

    int allNum = 0;//选中的订单商品数量
    String orderIds = "";//连贯订单编号

    private void preformOrder() {

        final ArrayList<BeanShopCar> arrayList_choose = new ArrayList<>();// 选中的商品
        allNum = 0;
        for (BeanShopCar beanShopCar : arrayList_shopcar) {
            if (beanShopCar.isChoose()) {
                orderIds += beanShopCar.getId() + ",";
                arrayList_choose.add(beanShopCar);
                allNum += beanShopCar.getList().size();
            }
        }
        if (allNum == 0) {
            showToast("请先选择商品");
            return;
        }
        if (orderIds.length() > 0) {
            orderIds = orderIds.substring(0, orderIds.length() - 1);
        }
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("user_id", userBean.getUser_id());
        hashMap.put("cart_id", orderIds);
        new HttpUtils().post(this, Constants.API_JIAOYAN, hashMap, null, HttpUtils.TYPE_ARRAY, new HttpUtils.HttpCallback() {
            @Override
            public void success(String msg, Object json) {
                if (msg.equals("库存校验成功")) {
                    //可以进入生成订单的页面
                    Intent intent = new Intent(mContext, ActivityOrderWrite.class);
                    intent.putExtra("array", arrayList_choose);
                    intent.putExtra("count", allNum);
                    intent.putExtra("price", all_prise);
                    intent.putExtra("ids", orderIds);
                    startActivity(intent);

                    return;
                } else {
                    //标红购物车
                }
            }

            @Override
            public void fail(String failMsg) {
                showToast(failMsg);
            }
        });
    }


    boolean hasChooseAll = false;

    double all_prise = 0;

    public void setMoney() {
        adapterShopCar.notifyDataSetChanged();
        all_prise = 0;//所有钱
        int chooseNum = 0;//所有人
        for (BeanShopCar bean : arrayList_shopcar) {
            if (bean.isChoose()) {
                for (BeanShopCar.goods goods : bean.getList()) {
                    try {
                        all_prise += goods.getNumber() * Double.parseDouble(goods.getShop_price());
                        chooseNum++;
                    } catch (Exception e) {
                    }

                }
            }
        }

        tv_all_parse.setText(all_prise + "");
        tv_hadChoose.setText("已选( " + chooseNum + ")");
    }

    int pagesize = 10;
    int page = 1;


    protected void getHttpDatas() {

        super.getHttpData();
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("user_id", userBean.getUser_id());
        hashMap.put("pagesize", pagesize + "");
        hashMap.put("pageindex", page + "");
        arrayList_shopcar.clear();
        adapterShopCar.notifyDataSetChanged();
        new HttpUtils().post(this, Constants.API_SHOP_CAR, hashMap, null, HttpUtils.TYPE_ARRAY, new HttpUtils.HttpCallback() {
            @Override
            public void success(String msg, Object json) {
                JSONArray jsonArray = (JSONArray) json;
                if (jsonArray.length() <= 0) {
                    icon_nodata.setVisibility(View.VISIBLE);
                    rv_shopcar.setVisibility(View.GONE);
                    tv_title_right.setVisibility(View.GONE);
                } else {
                    icon_nodata.setVisibility(View.GONE);
                    rv_shopcar.setVisibility(View.VISIBLE);
                    tv_title_right.setVisibility(View.VISIBLE);
                }
                for (int a = 0; a < jsonArray.length(); a++) {
                    try {
                        BeanShopCar bean = JSON.parseObject(jsonArray.getString(a), BeanShopCar.class);
                        arrayList_shopcar.add(bean);
                        if (tv_title_right.getText().equals("完成")) {
                            bean.setEdit(true);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                adapterShopCar.notifyDataSetChanged();
                hideProgress();
            }

            @Override
            public void fail(String failMsg) {
                showToast(failMsg);
                hideProgress();
            }
        });
    }

    public int STATE_CHANGE = 0, STATE_DEL = 1;
    String content = "";


    @Override
    public void onResume() {
        super.onResume();
        getHttpDatas();
    }

    private void changeShopcar(String id, int state) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("action", state == STATE_CHANGE ? "MODIFY" : "REMOVE");
        hashMap.put("id", id);
        hashMap.put("content", content);
        hashMap.put("user_id", userBean.getUser_id());
        showProgress();
        new HttpUtils().post(this, Constants.API_SHOPCAR_CHANGE, hashMap, null, HttpUtils.TYPE_NOTHING, new HttpUtils.HttpCallback() {
            @Override
            public void success(String msg, Object json) {
                showToast(msg);
                getHttpDatas();
            }

            @Override
            public void fail(String failMsg) {
                showToast(failMsg);
                hideProgress();
            }
        });

    }

    public boolean isEdit() {
        if (!tv_title_right.getText().equals("编辑")) {
            tv_title_right.callOnClick();
            return true;
        } else {
            return false;
        }
    }


}
